
var service = require('./service');
var express = require('express');
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
// 1. 创建一个路由容器
var router = express.Router();


router.get('/main', function (req, res) {
  service.commentList(function (commentList) {
    res.render('main.html', {
      commentList: commentList
    })
  });
});
//评论
router.get('/ask', function (req, res) {
  var isLogin= localStorage.getItem("isLogin")||"0";
  if(isLogin==="1"){//已登录
    res.render('ask.html')
  }else{//未登录
    res.redirect('/login')
  }

});

router.post('/ask', function (req, res) {
  console.log("req.body.id=="+req.body.id);
  service.saveComment(req.body, function (err) {
    if (err) {
      return res.status(500).send('Server error.')
    }
    res.redirect('/main')
  })
});

router.get('/comment', function (req, res) {
  var isLogin= localStorage.getItem("isLogin")||"0";
  if(isLogin==="1"){//已登录
    service.comment(req.query.id, function (comments) {
      var comment=JSON.parse(localStorage.getItem("comment"));
      res.render('comment.html',{
        comment:comment,
        comments:comments
      })
    });
  }else{//未登录
    res.redirect('/login')
  }

});

router.post('/comment', function (req, res) {
  service.saveComment(req.body,function (err) {
    res.redirect('/main')
  })

});


/*
 * 登录页面
 */
router.get('/login', function (req, res) {
  res.render('login.html')
});

/*
 * 登录
 */
router.post('/login', function (req, res) {
  console.log(req.body.id);
  service.login(req.body, function (data) {
    if (data.code !=0) {
      return res.status(500).send('Server error.')
    }
    res.redirect('/main')
  })
});


/*
 * 渲染添加页面
 */
router.get('/add', function (req, res) {
  res.render('add.html')
})

/*
 * 处理添加
 */
router.post('/add', function (req, res) {
  service.save(req.body, function (err) {
    if (err) {
      return res.status(500).send('Server error.')
    }
    res.redirect('/login')
  })
})


/*
 * 处理删除
 */
router.get('/delete', function (req, res) {
  service.deleteById(req.query.id, function (err) {
    res.redirect('/main')
  })
})




// 3. 把 router 导出
module.exports = router

